package com.bocloud.cmp.driver.providers.jd;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.bocloud.cmp.driver.providers.SecurityGroupDriver;
import com.bocloud.cmp.model.SecurityGroupModel;
import com.bocloud.common.model.BsmResult;
import com.google.common.collect.Lists;
import com.jcloud.cap.client.ClientConfig;
import com.jcloud.cap.client.IClient;
import com.jcloud.cap.client.JCloudClient;
import com.jcloud.cap.client.builder.v1.CreateSecurityGroupRequestBuilder;
import com.jcloud.cap.client.builder.v1.DeleteSecurityGroupRequestBuilder;
import com.jcloud.cap.client.builder.v1.QuerySecurityGroupDetailRequestBuilder;
import com.jcloud.cap.client.builder.v1.QuerySecurityGroupsRequestBuilder;
import com.jcloud.cap.client.exception.ClientException;
import com.jcloud.cap.client.exception.ServerException;
import com.jcloud.cap.client.http.HttpConfig;
import com.jcloud.cap.data.model.v1.CreateSecurityGroupResponse;
import com.jcloud.cap.data.model.v1.DeleteSecurityGroupResponse;
import com.jcloud.cap.data.model.v1.QuerySecurityGroupDetailResponse;
import com.jcloud.cap.data.model.v1.QuerySecurityGroupsResponse;
import com.jcloud.cap.data.model.v1.SecurityGroupResponse.SecurityGroup;

public class JdSecurityGroupDriver extends JdDriver implements SecurityGroupDriver {
	private static Logger logger = LoggerFactory.getLogger(JdSecurityGroupDriver.class);
	private IClient client;

	/**
	 * @param accessKey
	 * @param secretKey
	 * @param endpoint
	 */
	public JdSecurityGroupDriver(String accessKey, String secretKey, String endpoint, String region) {
		super(accessKey, secretKey, endpoint, region);
		ClientConfig config = new ClientConfig();
		HttpConfig httpConfig = new HttpConfig();
		// 调用地址
		httpConfig.setEndpoint(endpoint);
		httpConfig.setReadTimeout(20000);
		httpConfig.setConnectTimeout(20000);
		config.setHttpConfig(httpConfig);
		config.setCredential(this.getCredential().getCapCredential());
		client = new JCloudClient(config);
	}

	@Override
	public BsmResult list() {
		QuerySecurityGroupsRequestBuilder builder = QuerySecurityGroupsRequestBuilder.create();
		this.init(builder, "network", "querySecurityGroups", this.getRegion());
		try {
			QuerySecurityGroupsResponse response = client.send(builder.build());
			List<SecurityGroupModel> models = Lists.newArrayList();
			List<SecurityGroup> groups = response.getSecurityGroups();
			for (SecurityGroup group : groups) {
				String groupName = group.getName();
				if (groupName.equals("default") || groupName.equals("_jd_sg_user")) {
					continue;
				}
				SecurityGroupModel model = new SecurityGroupModel(group.getSecurityGroupId(), group.getName(),
						group.getDescription(), group.getCreateTime(), null);
				models.add(model);
			}
			return new BsmResult(true, models, "success");
		} catch (ClientException | ServerException e) {
			logger.error("List SecurityGroup [{}] exception!", e);
			return new BsmResult(false, "List SecurityGroup failed");
		}
	}

	@Override
	public BsmResult create(SecurityGroupModel group) {
		CreateSecurityGroupRequestBuilder builder = CreateSecurityGroupRequestBuilder.create();
		this.init(builder, "network", "createSecurityGroup", this.getRegion());
		try {
			CreateSecurityGroupResponse response = client
					.send(builder.name(group.getName()).description(group.getRemark()).build());
			return detail(response.getSecurityGroupId(), response.getRequestId());
		} catch (ClientException | ServerException e) {
			logger.error("createSecurityGroup [{}] exception!", e);
			return new BsmResult(false, "createSecurityGroup failed");
		}

	}

	@Override
	public BsmResult remove(String sgId) {
		DeleteSecurityGroupRequestBuilder builder = DeleteSecurityGroupRequestBuilder.create();
		this.init(builder, "network", "deleteFirewall", this.getRegion());
		try {
			DeleteSecurityGroupResponse response = client.send(builder.securityGroupId(sgId).build());
			return new BsmResult(true, response.getRequestId(), "success");
		} catch (ClientException | ServerException e) {
			logger.error("Reomve security group [{}] exception!", e);
			return new BsmResult(false, "Reomve security group failed");
		}
	}

	@Override
	public BsmResult detail(String sgId) {
		return detail(sgId, null);
	}

	private BsmResult detail(String sgId, String requestId) {
		QuerySecurityGroupDetailRequestBuilder builder = QuerySecurityGroupDetailRequestBuilder.create();
		this.init(builder, "network", "querySecurityGroupDetail", this.getRegion());
		try {
			QuerySecurityGroupDetailResponse response = client.send(builder.securityGroupId(sgId).build());
			SecurityGroup group = response.getSecurityGroup();
			if (null == group) {
				return new BsmResult(false, "该安全组不存在");
			}
			Date date = null == group.getCreateTime() ? new Date() : group.getCreateTime();
			SecurityGroupModel model = new SecurityGroupModel(group.getSecurityGroupId(), group.getName(),
					group.getDescription(), date, requestId);
			return new BsmResult(true, model, "success");
		} catch (ClientException | ServerException e) {
			logger.error("Query security group [{}] exception!", e);
			return new BsmResult(false, "Query security group failed");
		}
	}

}
